#!/usr/bin/env python
#
# This script is meant to produce packages that install files into the default
# user template as well as all other existing home directories. It will _not_
# deploy the files or directories to existing home directories if the given 
# home directory already contains the specified file.
#
import sys
import os
import tempfile
import shutil
import subprocess

if len(sys.argv) < 5:
	sys.stderr.write('Usage: %s <payload> <dest-path> <pkg-name> <version>\n' % (sys.argv[0]))
	sys.stderr.write('       payload: the file or directory to package and deploy\n')
	sys.stderr.write(' relative-path: destination path for the file\n')
	sys.stderr.write('      pkg-name: Desired name of the resulting package.\n')
	sys.stderr.write('       version: Desired version of the resulting package.\n')
	sys.exit(1)



thePayload = sys.argv[1]
theDestPath = sys.argv[2]
thePkgName = sys.argv[3];
thePkgVersion = sys.argv[4];

if not os.path.exists(thePayload):
	sys.stderr.write("ERROR: Unable to locate '%s'\n" % thePayload)
	sys.exit(1)


tmpPath = tempfile.mkdtemp()
payloadPath = "%s/payload" % tmpPath


if os.path.isdir(thePayload) == True:
	shutil.copytree(thePayload, payloadPath)
else:
	os.mkdir(payloadPath)
	shutil.copy(thePayload, payloadPath)


pkgPath = "%s/%s.pkg" % (os.getcwd(), thePkgName)
subprocess.call([
	"pkgbuild",
	"--root", payloadPath,
	"--version", thePkgVersion,
	"--install-location", theDestPath,
	"--identifier", "edu.denison.%s" % thePkgName,
	pkgPath])
shutil.rmtree(tmpPath)

subprocess.call([
	"/usr/local/munki/munkiimport",
	"--catalog=dev",
	"--min-os-ver=10.6",
  "-d", "" ,
	pkgPath])

os.remove(pkgPath)
